<template>
  <div>
    <el-empty v-if="userInfo === null" description="这里空空如也">
      <el-button type="primary" @click="goTo('/user/login')">去登录/注册</el-button>
    </el-empty>

    <el-descriptions v-else :column="2" direction="vertical" border title="用户信息">
      <el-descriptions-item label="邮箱">{{ userInfo.email }}</el-descriptions-item>
      <el-descriptions-item label="头像">
        <div>
          <!-- 头像展框 -->
          <el-avatar :src="avatarUrl" large />

          <!-- 上传头像按钮 -->
          <el-upload class="upload-demo" :http-request="customUpload" :on-success="getImage"
            :before-upload="beforeUpload" :show-file-list="false">
            <el-button size="small" type="primary">上传头像</el-button>
          </el-upload>
        </div>
      </el-descriptions-item>
      <el-descriptions-item label="昵称">{{ userInfo.username }}</el-descriptions-item>
      <el-descriptions-item label="性别">{{ userInfo.sex }}</el-descriptions-item>
      <el-descriptions-item label="生日">{{ userInfo.birthday }}</el-descriptions-item>
      <el-descriptions-item label="地区">{{ userInfo.district }}</el-descriptions-item>
    </el-descriptions>
  </div>
</template>

<script setup lang="ts">
import { useGoTo } from '@/hooks/useGoTo';
import axios from 'axios';
import { useUserStore } from '@/stores/userStore'; // 引入 Pinia store
import { onMounted, onUnmounted, computed, ref } from 'vue';
import { ElMessage } from 'element-plus';

const { goTo } = useGoTo();
const userStore = useUserStore(); // 使用 Pinia store

const userInfo = computed(() => userStore.user);
const avatarUrl = ref('');

async function getImage() {
  try {
    const response = await axios({
      method: 'get',
      url: `/api/user/getImage?email=${userInfo.value.email}`,
      responseType: 'blob',
    });
    avatarUrl.value = URL.createObjectURL(response.data);
  } catch (error) {
    console.error('获取头像失败:', error);
  }
}

async function getInfo() {
  try {
    const params = {
      email: userInfo.value.email,
    };
    const response = await axios.get('/api/user/getUserData', { params });
    userStore.setUser(response.data.data);
    console.log(response.data.data); 
  } catch (error) {
    console.error(error);
  }
}

const customUpload = async (options: any) => {
  const file = options.file;
  const formData = new FormData();
  formData.append('avatars', file);
  formData.append('email', userInfo.value.email);

  try {
    const response = await axios.put('/api/user/setAvatars', formData);
    ElMessage({
      message: '文件上传成功',
      type: 'success',
    });
  } catch (error) {
    ElMessage({
      message: '文件上传失败: ' + error.message,
      type: 'error',
    });
  }
};

const beforeUpload = (file: any) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 5;
  if (!isJPG) {
    ElMessage({
      message: '上传头像图片只能是 JPG/PNG 格式!',
      type: 'warning',
    });
    return false;
  }
  if (!isLt2M) {
    ElMessage({
      message: '上传头像图片大小不能超过 5MB!',
      type: 'warning',
    });
    return false;
  }
  return true;
};

onMounted(() => {
  if (userInfo.value) {
    getInfo();
    getImage();
  }
});

onUnmounted(() => {
  if (avatarUrl.value) {
    URL.revokeObjectURL(avatarUrl.value);
  }
});
</script>

<style scoped></style>